package pubM

import (
	"fmt"
	"db2s/global"
	"db2s/outPut"
	"db2s/ref"
	mq "db2s/topic-mq"
	"reflect"
)

type BreakActionEr interface {
	Read() (err error)
	Write(d any) (err error)
	GetRes(options string) (res any)
}

func NewBreakObject(p any) BreakActionEr {
	switch p.(type) {
	case BreakPoint:
		pp := p.(BreakPoint)
		return &pp
	case *BreakPoint:
		return p.(*BreakPoint)
	}
	return nil
}

type BreakPoint struct {
	FileName       string                `json:"name"`
	Truncate       bool                  `json:"truncate"`
	RSymbol        string                `json:"symbol"`
	ContinueResult map[string]int        `json:"result"`
	FilePoint      outPut.FileOperations `json:"point"`
}

func (b *BreakPoint) Init() (err error) {
	if len(b.RSymbol) == 0 {
		b.RSymbol = "\n"
	}
	b.ContinueResult = make(map[string]int)
	b.FilePoint = outPut.NewFileOperations(outPut.Tex{FileName: b.FileName, Truncate: b.Truncate, RSymbol: b.RSymbol})
	if err = b.FilePoint.Init(); err != nil {
		err = ref.ErrAddPrintf("Init", err)
		return
	}
	return
}
func (b *BreakPoint) breakPointQuit(event string,_ any) (r any) {
	ref.MyWaitDel("breakPoint")
	//Info(fmt.Sprintf("%v When the breakpoint resume function is enabled, table set %v will be skipped.", "getBreakPointTableList", b.ContinueResult))
	return
}
func schemaMetaExecFuncParameterSplit(f []any) (baseParameter map[string]any, chanParameter any, useParameter []any) {
	baseParameter = f[0].(map[string]any)
	chanParameter = f[1]
	useParameter = f[2:]
	return
}
func (b *BreakPoint) breakPointList(event string,f any) (r any) {
	if f == nil || len(f.([]any)) == 0 {
		return
	}
	_, chanParameter, _ := schemaMetaExecFuncParameterSplit(f.([]any))
	switch chanParameter.(type) {
	case *string:
		b.ContinueResult[*chanParameter.(*string)]++
	}
	return
}
func (b *BreakPoint) breakPointObjectInit(m any) (send *mq.MonitorMsgMq) {
	send = mq.NewMonitorMsgMq()
	send.SendMsg.MsgModifyKey = m.(chan any)
	send.NormalQuit = global.EFunc{FuncName: b.breakPointQuit}
	send.ExecFunc = append(send.ExecFunc, global.EFunc{FuncName: b.breakPointList})
	return
}
func (b *BreakPoint) Read() (err error) {
	var m any
	if err = b.Init(); err != nil {
		return
	}
	if m, err = b.FilePoint.Read(); err != nil {
		return err
	}
	ref.MyWaitAdd("breakPoint")
	b.breakPointObjectInit(m).NormalChanSendMsg("syMGetBreakPointTableList")
	return
}
func (b *BreakPoint) Write(d any) (err error) {
	switch d.(type) {
	case string:
		if err = b.FilePoint.Write("", fmt.Sprintf("%v", d)); err != nil {
			return
		}
	}
	return
}
func (b *BreakPoint) GetRes(options string) (res any) {
	v := reflect.ValueOf(b).Elem() // 获取指向 BreakPoint 的值
	t := v.Type()                  // 获取 BreakPoint 的类型
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		jsonTag := field.Tag.Get("json")

		if jsonTag == options {
			return v.Field(i).Interface() // 返回对应字段的值
		}
	}
	return nil // 如果没有找到对应字段，返回 nil
}
